//
//  Fraction.m
//  02_分数
//
//  Created by dllo on 16/7/5.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "Fraction.h"

@implementation Fraction

- (instancetype)initWithNumerator:(NSInteger)numerator
                      denominator:(NSInteger)denominator {
    self = [super init];
    if (self) {
        _numerator = numerator;
        _denominator = denominator;
    }
    if (self.denominator == 0) {
        NSLog(@"由于分数的分母为0,以下结果均是未定义的");
    }
    return self;
}

+ (instancetype)fractionWithNumerator:(NSInteger)numerator
                          denominator:(NSInteger)denominator {
    return [[[Fraction alloc] initWithNumerator:numerator denominator:denominator] autorelease];
}

- (Fraction *)add:(Fraction *)fraction {

    Fraction *newFraction = [[Fraction alloc] init];
    newFraction.numerator = self.numerator * fraction.denominator + self.denominator * fraction.numerator;
    newFraction.denominator = self.denominator * fraction.denominator;
    [newFraction reduce];
    return newFraction;
}

- (NSString *)description {
    return [NSString stringWithFormat:@"%ld / %ld", self.numerator, self.denominator];
}

- (Fraction *)subtract:(Fraction *)fraction {

    Fraction *newFraction = [[Fraction alloc] init];
    newFraction.numerator = self.numerator * fraction.denominator - self.denominator * fraction.numerator;
    newFraction.denominator = self.denominator * fraction.denominator;
    [newFraction reduce];
    return newFraction;
}

- (Fraction *)multiply:(Fraction *)fraction {

    Fraction *newFraction = [[Fraction alloc] init];
    newFraction.numerator = self.numerator * fraction.numerator;
    newFraction.denominator = self.denominator * fraction.denominator;
    [newFraction reduce];
    return newFraction;
}

- (Fraction *)divide:(Fraction *)fraction {

    Fraction *newFraction = [[Fraction alloc] init];
    newFraction.numerator = self.numerator * fraction.denominator;
    newFraction.denominator = self.denominator * fraction.numerator;
    [newFraction reduce];
    return newFraction;
}

- (NSInteger)compare:(Fraction *)fraction {

    return self.numerator * fraction.denominator - self.denominator * fraction.numerator;
}

- (void)reduce {

    NSInteger n = self.numerator;
    NSInteger d = self.denominator;
    NSInteger r = 0;
    
    while(d) {
        r = n % d;
        n = d;
        d = r;
    }
    // 最后n是最大公约数
    self.numerator /= n;
    self.denominator /= n;
}

@end
